package com.edison.democommon.util;


import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author edison
 * this is a util class for jwt draft
 */

public class JWTUntil {


    private static final Logger logger = LoggerFactory.getLogger(JWTUntil.class);
    private static final String SECRET = "secret";
    // 10 S
    private static  int expiration = 1000 * 10;

    private JWTUntil() {
        throw new IllegalStateException("Utility class");

    }

    public static String generateToken(Map<String, Object> map) {
        return   Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .setIssuedAt(new Date())
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    public  static boolean validateToken(String token) {
        try   {
         getTokenBody(token);
        return true;
    } catch (ExpiredJwtException e) {
        logger.warn("Request to parse expired JWT : {} failed : {}", token, e.getMessage());
    } catch (UnsupportedJwtException e) {
        logger.warn("Request to parse unsupported JWT : {} failed : {}", token, e.getMessage());
    } catch (MalformedJwtException e) {
        logger.warn("Request to parse invalid JWT : {} failed : {}", token, e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.warn("Request to parse empty or null JWT : {} failed : {}", token, e.getMessage());
    } catch (SignatureException e) {
            logger.warn("Request to parse JWT with invalid signature : {} failed : {}", token, e.getMessage());
    } catch (Exception e) {
            logger.warn("Request to parse JWT with unknown exception : {} failed : {}", token, e.getMessage());
    }
        return false;
    }

    private static Claims getTokenBody(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }





    public static String refreshToken(String token) {
        return generateToken(getTokenBody(token));
    }



}

